package xyz.longicorn.driver.controller;

import cn.hutool.core.net.URLEncodeUtil;
import cn.hutool.http.HttpUtil;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xyz.longicorn.driver.pojo.FileInfo;
import xyz.longicorn.driver.service.FileService;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

@RestController
public class DownloadController {
    @Resource
    private FileService fileService;

    @SneakyThrows
    @RequestMapping("/download")
    public void download(String id, HttpServletResponse response) {
        System.out.println(id);
        String[] idList = id.split(",");
        final FileInfo file = fileService.getById(id);
        // TODO 验证文件的信息

        response.setHeader("Content-Disposition", "attachment; filename="+file.getName()
                +"; filename*=utf-8''" + URLEncodeUtil.encode(file.getName()));
        final ServletOutputStream os = response.getOutputStream(); // 获取网络输出流
        InputStream is = null;
        if(file.getPath().startsWith("http")){
            // 对于网络文件 直接 先下载在输出
            URL url = new URL(file.getPath());
            URLConnection connection = url.openConnection(); // 通过网址打开一个连接
            is = connection.getInputStream();//获取文件内容的输入流
        }else{
            is = new FileInputStream(file.getPath()); // 获取文件输入流
        }

        byte[] bytes = new byte[10240];
        int len;
        while ((len = is.read(bytes)) != -1) {
            os.write(bytes, 0, len);
        }
        os.close();
        is.close();

//        response.getWriter().println("xxx");
    }

}
